import { delAddressReq, editAddressReq } from '@/api/logistics'
import useGetArea from '@/hooks/useGetArea'
import { UseModalResult } from '@/hooks/useModal'
import { AreaVerify, validateIsPureDigital } from '@/utils/validator'
import { PlusOutlined } from '@ant-design/icons'
import { Modal, Table, Form, Input, Row, Col, Button, Cascader, message } from 'antd'
import { useState } from 'react'
import { useAddressColumns } from '../columns'
import { SupplierTransportAddressVO } from '../types'
interface IProps {
  modalInstance: UseModalResult<any>
  reqestFunction: (...reset: any) => Promise<any>
  addressList: SupplierTransportAddressVO[]
  setaddressList: React.Dispatch<React.SetStateAction<SupplierTransportAddressVO[]>>
  selectedRowInfos: Record<string, any>[]
  getAddressList: () => void
}
const AddressModal = (props: IProps) => {
  const [areaList, setareaList] = useState<number[]>([])
  const { AreaOptions, loadAreaData } = useGetArea(areaList)
  const [addressName, setaddressName] = useState({
    province: '',
    city: '',
    area: '',
  })
  const grid = { xs: 24, sm: 24, md: 12, lg: 8, xl: 8, xxl: 8 }
  const onSave = async (rows: SupplierTransportAddressVO, isReload?: boolean) => {
    if (isReload) {
      props.getAddressList && props.getAddressList()
      return
    }
    if (!rows.contacts) {
      message.warning('请输入提货联系人！')
      return
    }
    if (!rows.phone) {
      message.warning('请输入联系人电话！')
      return
    }
    if (!/^\d+$/.test(rows?.phone + '')) {
      message.warning('联系人电话格式不正确')
      return
    }
    if (!rows.receivingAddress || rows.receivingAddress.length != 3) {
      message.warning('请选择收货地址！')
      return
    }
    if (!rows.address) {
      message.warning('请输入详细地址！')
      return
    }
    const res = await editAddressReq(rows)
    if (res.code == 200) {
      message.success('操作成功')
      props.getAddressList && props.getAddressList()
    }
  }
  const onDel = async (rows: SupplierTransportAddressVO) => {
    const res = await delAddressReq({ id: rows.id, supplierId: rows.supplierId })
    if (res.code == 200) {
      message.success('操作成功')
      props.getAddressList && props.getAddressList()
    }
  }
  return (
    <Modal
      width={1200}
      title="配置提货地址"
      footer={null}
      maskClosable={false}
      open={props.modalInstance.open}
      onCancel={props.modalInstance.closeModal}
      onOk={() => {
        props.modalInstance.handleSubmit(() =>
          props.reqestFunction({
            ...props.modalInstance.form.getFieldsValue(),
          }),
        )
      }}
      confirmLoading={props.modalInstance.confirmLoading}
    >
      <div className="addressmodal_main_wrap">
        <div className="logistics_demand-form">
          <Form form={props.modalInstance.form} layout="inline" labelAlign="left" labelWrap initialValues={{ ac: 0 }}>
            <Row gutter={[20, 20]} style={{ marginBottom: 12 }}>
              <Col {...grid}>
                <Form.Item label="提货联系人" name="contacts" rules={[{ required: true, message: '请输入提货联系人' }]}>
                  <Input placeholder="请输入提货联系人"></Input>
                </Form.Item>
              </Col>
              <Col {...grid}>
                <Form.Item
                  label="联系人电话"
                  name="phone"
                  rules={[{ required: true, message: '请输入联系人电话' }, { validator: validateIsPureDigital }]}
                >
                  <Input placeholder="请输入联系人电话"></Input>
                </Form.Item>
              </Col>
              <Col {...grid}>
                <Form.Item
                  label="收货地址"
                  name="receivingAddress"
                  rules={[
                    { required: true, message: '请选择收货地址' },
                    {
                      validator: AreaVerify,
                    },
                  ]}
                >
                  <Cascader
                    options={AreaOptions}
                    loadData={loadAreaData}
                    changeOnSelect
                    placeholder="请选择收货地址"
                    onChange={(_, address) => {
                      setaddressName({
                        province: address[0]?.label,
                        city: address[1]?.label,
                        area: address[2]?.label,
                      })
                    }}
                  ></Cascader>
                </Form.Item>
              </Col>
              <Col {...grid}>
                <Form.Item label="详细地址" name="address" rules={[{ required: true, message: '请输入详细地址' }]}>
                  <Input.TextArea rows={1} placeholder="请输入详细地址" showCount maxLength={100}></Input.TextArea>
                </Form.Item>
              </Col>
              <Col {...grid} style={{ alignSelf: 'flex-end' }}>
                <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() =>
                    props.modalInstance.handleSubmit((vals) =>
                      props.reqestFunction({
                        ...vals,
                        provinceId: vals?.receivingAddress[0],
                        cityId: vals?.receivingAddress[1],
                        areaId: vals?.receivingAddress[2],
                        supplierId: props?.selectedRowInfos[0]?.supplierId,
                        supplierCode: props?.selectedRowInfos[0]?.supplierCode,
                        ...addressName,
                      }),
                    )
                  }
                >
                  添加
                </Button>
              </Col>
            </Row>
          </Form>
        </div>
        <Table
          style={{ marginTop: 24 }}
          bordered
          size="small"
          columns={useAddressColumns({
            addressList: props.addressList,
            setaddressList: props.setaddressList,
            AreaOptions,
            loadAreaData,
            setareaList,
            onSave,
            onDel,
          })}
          dataSource={props?.addressList || []}
          rowKey="id"
          scroll={{ x: 600, y: 400 }}
          pagination={false}
          rowHoverable={false}
          rowClassName={(_, index) => {
            return index % 2 === 0 ? '' : 'zebra-row-odd'
          }}
        />
      </div>
    </Modal>
  )
}
export default AddressModal
